package cn.tgq.ioc.overview.container;

import cn.tgq.ioc.overview.model.User;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Map;


/**
 * 注解能力 {@link org.springframework.context.ApplicationContext} 作为 IoC 容器示例
 *
 * @author <a href="mailto:mercyblitz@gmail.com">Cloud</a>
 * @since 2021-11-13
 */
@Configuration
public class AnnotationApplicationContextAsIoCContainer {

    public static void main(String[] args) {
        // 创建 BeanFactory 容器
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        // 将当前类 AnnotationApplicationContextAsIoCContainerDemo 作为配置类（Configuration Class）
        context.register(AnnotationApplicationContextAsIoCContainer.class);
        // 启动应用上下文
        context.refresh();
        lookupCollectionByType(context);
        // 关闭应用上下文
        context.close();
    }

    /**
     * 通过 Java 注解的方式，定义了一个 Bean
     */
    @Bean
    public User user() {
        User user = new User();
        user.setId(1L);
        user.setName("Cloud");
        return user;
    }

    private static void lookupCollectionByType(BeanFactory beanFactory) {
        if (beanFactory instanceof ListableBeanFactory) {
            ListableBeanFactory listableBeanFactory = (ListableBeanFactory) beanFactory;
            Map<String, User> users = listableBeanFactory.getBeansOfType(User.class);
            System.out.println("查找到的所有的 User 集合对象：" + users);
        }
    }
}
